package com.s3u4.demo.zookeeper.base;

import com.s3u4.demo.zookeeper.ZkConfig;
import org.apache.zookeeper.*;

/**
 * 创建组
 * Created by Captain on 01/08/2017.
 */
public class CreateGroup extends ConnectionWatcher {

    public void create(String key,String value){
        try {
            if ( zooKeeper.exists(key,false) != null ){
                zooKeeper.create(key, value != null ? value.getBytes(ZkConfig.CHARSET) : null, ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
            } else {
                zooKeeper.setData(key, value != null ? value.getBytes(ZkConfig.CHARSET) : null,-1);
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void create(String paramPath) throws KeeperException, InterruptedException {
        if ( !paramPath.startsWith("/") ){
            paramPath = "/" + paramPath;
        }
        String[] nodes = paramPath.substring(1).split("/");
        if ( nodes.length > 0 ){
            String path = "";
            for ( int i = 0 ; i < nodes.length ; i++ ){
                path += "/" + nodes[i];
                if ( zooKeeper.exists(path,false) == null ) {
                    String createPath = zooKeeper.create(path,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                    System.out.println("Created : " + createPath);
                } else {
                    System.out.println("Node : [" + path + "] has exists...");
                }
            }
        } else {
            if ( zooKeeper.exists(paramPath,false) != null ) {
                String createPath = zooKeeper.create(paramPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                System.out.println("Created : " + createPath);
            } else {
                System.out.println("Node : [" + paramPath + "] has exists...");
            }
        }
    }


    public static void main(String[] args) throws Exception {

        CreateGroup createGroup = new CreateGroup();
        createGroup.connect(ZkConfig.ZK_HOST);
        createGroup.create("/zk-node/key1","value1");
//        createGroup.create("/demo-zookeeper/node2");
//        createGroup.create("/demo-zookeeper/node3");
        createGroup.close();

    }


}
